using System;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using ai520v.Data;
using ai520v.Models;
using Microsoft.EntityFrameworkCore;

namespace ai520v.Services
{
    public class UserService
    {
        private readonly ApplicationDbContext _context;

        public UserService(ApplicationDbContext context)
        {
            _context = context;
        }

        public async Task<(bool success, string message)> RegisterAsync(string username, string password, string phone)
        {
            try
            {
                // 检查手机号是否已存在
                var existingUser = await _context.Users.FirstOrDefaultAsync(u => u.Phone == phone);
                if (existingUser != null)
                {
                    return (false, "该手机号已被注册");
                }

                // 生成盐值
                var salt = GenerateSalt();
                // 生成密码哈希
                var passwordHash = HashPassword(password, salt);

                var user = new User
                {
                    Username = username,
                    PasswordHash = passwordHash,
                    Phone = phone,
                    Salt = salt,
                    CreatedAt = DateTime.Now,
                    UpdatedAt = DateTime.Now,
                    LastLoginAt = DateTime.Now
                };

                _context.Users.Add(user);
                await _context.SaveChangesAsync();

                return (true, "注册成功");
            }
            catch (Exception ex)
            {
                return (false, "注册失败：" + ex.Message);
            }
        }

        private string GenerateSalt()
        {
            byte[] salt = new byte[16];
            using (var rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(salt);
            }
            return Convert.ToBase64String(salt);
        }

        private string HashPassword(string password, string salt)
        {
            using (var sha256 = SHA256.Create())
            {
                var passwordBytes = Encoding.UTF8.GetBytes(password + salt);
                var hashBytes = sha256.ComputeHash(passwordBytes);
                return Convert.ToBase64String(hashBytes);
            }
        }
    }
}